// 用localstorage模拟chrome.storage.local
class ExtensionStorageSimulator {
  // eslint-disable-next-line default-param-last
  constructor(namespace = 'ext', secret) {
    this.namespace = namespace;
    this.secret = secret;
  }

  async set(items) {
    Object.entries(items).forEach(([key, value]) => {
      const data = this.secret ? this.encrypt(value) : JSON.stringify(value);
      localStorage.setItem(`${this.namespace}_${key}`, data);
    });
  }

  async get(key) {
    let result = null;
    const data = localStorage.getItem(`${this.namespace}_${key}`);

    if (data) {
      result = this.secret ? this.decrypt(data) : JSON.parse(data);
    }

    return Promise.resolve(result);
  }

  static encrypt(data) {
    /* 加密实现 */
    return data;
  }

  static decrypt(data) {
    /* 解密实现 */
    return data;
  }

  // 事件监听绑定
  onChanged(callback) {
    window.addEventListener('storage', (e) => {
      if (e.key.startsWith(`${this.namespace}_`)) {
        const change = { [e.key]: { newValue: e.newValue } };
        callback(change);
      }
    });
  }
}


const storage  = new ExtensionStorageSimulator();

console.log('测试')
console.log(storage)

storage.set('test', '123')

storage.get('test').then(res => {
  console.log(res)
})

export default {
  runtime: {
    getManifest() {
      return {
        version: '1.29.9',
      };
    },
    onMessage: {
      addListener() {},
      getURL(url) {
        return url;
      },
    },
  },
  // storage: new ExtensionStorageSimulator(),
  storage: {
    local: {
      onChanged: {
        addListener() {},
        removeListener() {},
      },
      set() {
        return {};
      },
      get(key) {
        if (key === 'pinnedWorkflows') {
          return Promise.resolve({});
        }
        if (key === 'workflowStates') {
          return {
            workflowStates: {
              loadData() {},
            },
          };
        }
        return {};
      },
      remove() {},
    },
  },
  // tabs: {
  // query() {
  //   return [];
  // },
  // onCreated: {
  //   addListener() {},
  // },
  // onActivated: {
  //   addListener() {},
  // },
  // onCommitted: {
  //   addListener() {},
  // },
  // },
  // webNavigation: {
  //   onCommitted: {
  //     removeListener() {},
  //   },
  // },
};
